<template>
  <div class="login">
    <div class="login-con">
      <ul class="menu-tab">
        <li
          v-for="item in MenuData"
          :class="item.current ? 'current' : ''"
          :key="item.type"
          @click="changeMenu(item)"
        >
          {{ item.txt }}
        </li>
      </ul>
    </div>

    <!--  表单部分开始 -->
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item prop="username">
        <label for="">账号：</label>
        <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>

      <el-form-item prop="password">
        <label for="">密码：</label>
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
          minlength="6"
          maxlength="15"
        />
      </el-form-item>

      <el-form-item prop="passwords" v-show="model === 'reg'">
        <label for="">重复密码：</label>
        <el-input
          v-model="ruleForm.passwords"
          type="password"
          minlength="6"
          maxlength="15"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="btnbool"
          type="primary"
          class="login-btn block"
          @click="submitForm(ruleFormRef)"
          >{{ model === "login" ? "登录" : "注册" }}</el-button
        >
      </el-form-item>
    </el-form>
    <!--  表单部分结束 -->
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from "vue";
import type { FormInstance } from "element-plus";

import * as ck from "@/utils/verfifcation"; // 引入正则
import link from "@/api/Link";
import apiUrl from "@/api/url";
import { ElMessage } from "element-plus";
import useMd5 from "@/hook/index";

import { useRouter } from "vue-router";
let router = useRouter(); // 接收 useRouter,实现跳转页面

const MenuData = reactive([
  {
    txt: "登录",
    current: true,
    type: "login",
  },
  {
    txt: "注册",
    current: false,
    type: "reg",
  },
]);

const model = ref("login");
// 获取开发环境的路径
// onMounted(() => {
//   console.log(process.env.VUE_APP_API);
// });

// eslint-disable-next-line @typescript-eslint/no-explicit-any
let changeMenu = (item: any) => {
  MenuData.forEach((ele) => {
    // 让所有的元素的current变为 false
    ele.current = false;
  });
  // 让当前的元素变为 true
  item.current = true;
  // 点击的时候让model的值变为响应的type，也就是修改保存点击的状态
  model.value = item.type;
};

// 表单部分开始
const ruleFormRef = ref<FormInstance>();

const checkUser = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("邮箱不能为空！"));
  } else if (ck.CkEmil(value)) {
    return callback(new Error("邮箱格式不正确！"));
  } else {
    callback();
  }
};

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("密码不能为空！！"));
  } else if (ck.CkPass(value)) {
    callback(new Error("密码格式错误，6至15位的字母+数字"));
  } else {
    callback();
  }
};

const validatePass2 = (rule: any, value: any, callback: any) => {
  // 因为登录没有重复密码 所以在登录的时候跳过
  if (model.value === "login") {
    callback();
  }

  if (value === "") {
    callback(new Error("重复密码不能为空！！"));
  } else if (value !== ruleForm.password) {
    callback(new Error("两次密码不一致"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  username: "",
  password: "",
  passwords: "",
});

let btnbool = ref(true); // 控制按钮是否能点击，默认为true不能点击
// 监听数据控制按钮是否能点击
watch(ruleForm, (newval, oldval) => {
  // 如果是登录界面
  if (model.value === "login") {
    // 判断登录界面的两个输入框是否有值
    if (newval.username != "" && newval.password != "") {
      btnbool.value = false; // 解除按钮禁用
    } else {
      btnbool.value = true; // 按钮禁用
    }
    // 如果是注册界面
  } else {
    // 判断注册界面的三个输入框是否有值
    if (
      newval.username != "" &&
      newval.password != "" &&
      newval.passwords != ""
    ) {
      btnbool.value = false; // 解除按钮禁用
    } else {
      btnbool.value = true; // 按钮禁用
    }
  }
});

//这里设置以哪一种方式触发表单验证，失去焦点验证
const rules = reactive({
  password: [{ validator: validatePass, trigger: "blur" }],
  passwords: [{ validator: validatePass2, trigger: "blur" }],
  username: [{ validator: checkUser, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      // 如果是登录界面
      if (model.value === "login") {
        // console.log("登录");
        // 配置数据格式
        let data = {
          name: ruleForm.username,
          pwd: useMd5(ruleForm.password).value, // 使用md5加密
        };
        link(apiUrl.register, "GET", {}, data).then((ok: any) => {
          if (ok.data.length !== 0) {
            ElMessage("登录成功");
            // 登录成功跳转到首页
            router.push("/home");
          } else {
            ElMessage.error("登录失败");
          }
        });

        // 如果是注册界面
      } else {
        // 配置数据格式
        let data = {
          name: ruleForm.username,
          pwd: useMd5(ruleForm.password).value, // 使用md5加密
        };
        // 如果是注册的时候就发送请求，返回注册数据到mock
        link(apiUrl.register, "POST", data).then((ok: any) => {
          // console.log(ok);
          // 如果ok.data里面不为空，就提示注册成功。否则提示注册失败
          if (Object.keys(ok.data).length !== 0) {
            ElMessage("注册成功");
            // 注册成功跳到登录界面
            model.value = "login";
            // 对应的样式也跟着变化
            MenuData.forEach((ele) => {
              ele.current = false;
            });
            MenuData[0].current = true;
          } else {
            ElMessage.error("注册失败");
          }
        });
      }
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };
// 表单部分结束
</script>

<style lang="scss">
.login {
  background-color: #0b2b42;
  height: 100%;
}
html,
body,
#app {
  height: 100%;
}

.menu-tab {
  list-style: none;
  text-align: center;
  li {
    margin-top: 20px;
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    cursor: pointer;
    color: #fff;
    border-radius: 5px;
    background-color: lightslategray;
    margin-left: 10px;
    margin-bottom: 10px;
  }
  .current {
    background-color: deeppink;
  }
}
.demo-ruleForm {
  width: 40%;
  margin: 50px auto;
  label {
    display: block;
    color: #fff;
    font-size: 15px;
    margin-bottom: 5px;
  }
}
.block {
  display: block;
  width: 100%;
}
.login-btn {
  margin-top: 10px;
}
</style>
